﻿using ER.Dynamic;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace ER.Tests.DynamicWebApp.Data.Dynamic
{
    public class RuntimeDbContext
    {
        static string webconfig_connectionString = "ConnectionString";
        public static readonly TypeEmiter TypeDbContextEmiter;
        static RuntimeDbContext()
        {
            TypeEmiter typeStudentEmiter = Emiter.CreateTypeEmiter("ER.Tests.DynamicWebApp.Data.Student");
            typeStudentEmiter.AddPropertyEmiter("StudentId", typeof(int));
            typeStudentEmiter.AddPropertyEmiter("Name", typeof(String));
            typeStudentEmiter.AddPropertyEmiter("Class", typeof(String));
            typeStudentEmiter.Emit();

            TypeEmiter typeEmployeeEmiter = Emiter.CreateTypeEmiter("ER.Tests.DynamicWebApp.Data.Employee");
            typeEmployeeEmiter.AddPropertyEmiter("EmployeeId", typeof(int));
            typeEmployeeEmiter.AddPropertyEmiter("Name", typeof(String));
            PropertyEmiter ageProp = typeEmployeeEmiter.AddPropertyEmiter("Age", typeof(int));
            typeEmployeeEmiter.Emit();

            TypeDbContextEmiter = Emiter.CreateTypeEmiter("ER.Tests.DynamicWebApp.Data.RuntimeDbContext");
            TypeDbContextEmiter.BaseType = typeof(DbContext);
            TypeDbContextEmiter.AddConstructorEmiter(new []{typeof(string)});
            var stDbSet = typeof(DbSet<>).MakeGenericType(typeStudentEmiter);
            var emDbSet = typeof(DbSet<>).MakeGenericType(typeEmployeeEmiter);
            RuntimeDbContext.TypeDbContextEmiter.AddPropertyEmiter("Students", stDbSet);
            RuntimeDbContext.TypeDbContextEmiter.AddPropertyEmiter("Employees", emDbSet);
            TypeDbContextEmiter.Emit();
        }
        public static DbContext CreateDbContext()
        {
            var c = TypeDbContextEmiter.Type.GetConstructor(new[] { typeof(string) });
            var db = c.Invoke(new[] { webconfig_connectionString });
            return RuntimeDbContext.TypeDbContextEmiter.CreateObject(webconfig_connectionString) as DbContext;
        }
    }
}